﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Security.Principal;
using System.Configuration;
using TravelSite.DAL;
using TravelSite.DAL.Repositories;

namespace TravelSite
{
    public class Global : System.Web.HttpApplication
    {

        void Application_BeginRequest(Object sender, EventArgs e)
        {
            bool useSSL = (ConfigurationManager.AppSettings["useSSL"] != null) && bool.Parse(ConfigurationManager.AppSettings["useSSL"]);

            if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && useSSL)
            {
                Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
            }
        }

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["IsDevelopmentEnvironment"])) return;

            System.Exception ex = Server.GetLastError();
            try
            {
                using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
                {
                    repo.LogAdd(ex, Context, Context.Session["userName"] == null ? "" : Context.Session["userName"].ToString());
                }

                Response.Write("Unexpected error occurs. See log for details");
                Server.ClearError();
            }
            catch (Exception exNew)
            {
                Response.Write("Unexpected error occurs (" + ex.Message + " -> " + exNew.Message + ")<br/>" + ex.StackTrace);
                Server.ClearError();
            }

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}
